export function formatList (arr, field, total, posindex) {
  let data = []
  for (let i = 0; i < total; i++) {
    let nowObj = {}
    let nowArr = []
    for (let [index, val] of arr.entries()) {
      if (index >= (posindex + field.length * i) && index <= (posindex + field.length * (i + 1))) {
        nowArr.push(val)
      }
    }
    for (let j = 0; j < field.length; j++) {
      nowObj[field[j]] = nowArr[j]
    }
    data.push(nowObj)
  }
  return data
}

export function clone (obj) {
  let copy

  // 处理3种简单类型，以及null或undefined
  if (obj == null || typeof obj !== 'object') return obj

  // 处理 Date
  if (obj instanceof Date) {
    copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }

  // 处理 Array
  if (obj instanceof Array) {
    copy = []
    for (let i = 0, len = obj.length; i < len; i++) {
      copy[i] = clone(obj[i])
    }
    return copy
  }

  // 处理 Object
  if (obj instanceof Object) {
    copy = {}
    for (let attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr])
    }
    return copy
  }

  throw new Error('无法复制obj！ 它的类型不受支持。')
}


/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 * @default 用例 {hh}:{ii}:{ss}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime (time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

// 计算当前涨跌值，将精确到后四位
export function upsAndDowns (nowp, yesp) {
  // 当前 昨结
  // console.log(nowp, yesp)
  // let difference = parseFloat(nowp) - parseFloat(yesp)
  let difference = parseFloat(nowp - yesp) * 1

  // 如果不是一个数字，返回null
  if (isNaN(difference)) {
    return '---';
  }
  // 将浮点数四舍五入，取小数点后4位
  let f = difference.toFixed(5);
  return f;
}

export function figureRange (n, y) {
  // 先计算涨跌
  let difference = parseFloat(n) - parseFloat(y)
  if (isNaN(difference)) {
    return '---';
  }
  // 将浮点数四舍五入，取小数点后4位
  // difference = Math.round(difference * 10000) / 10000;

  // 再计算幅度
  let business = difference / y;

  // 如果不是一个数字，返回null
  if (isNaN(business)) {
    return '---';
  }
  // 将浮点数四舍五入，取小数点后2位
  //let r = Math.round(business * 100) / 100;
  let r = (business * 100).toFixed(2);
  return r;
}


/**
 * 快速排序
 * @param {array} arr
 * @param {number} left // 排序区间左 [选填]
 * @param {number} right // 排序区间右[选填]
 * @returns {array} 
 */
export function quickSort (arr, left, right) {
  var len = arr.length,
    partitionIndex,
    left = typeof left != 'number' ? 0 : left,
    right = typeof right != 'number' ? len - 1 : right;

  if (left < right) {
    partitionIndex = partition(arr, left, right);
    quickSort(arr, left, partitionIndex - 1);
    quickSort(arr, partitionIndex + 1, right);
  }
  return arr;
}

export function sortReverse (arr, left, right) {
  var len = arr.length,
    partitionIndex,
    left = typeof left != 'number' ? 0 : left,
    right = typeof right != 'number' ? len - 1 : right;

  if (left < right) {
    partitionIndex = partitionReverse(arr, left, right);
    sortReverse(arr, left, partitionIndex - 1);
    sortReverse(arr, partitionIndex + 1, right);
  }
  return arr;
}

function partition (arr, left, right) {     //分区操作
  var pivot = left,                      //设定基准值（pivot）
    index = pivot + 1;
  for (var i = index; i <= right; i++) {
    if (arr[i].Sequence * 1 < arr[pivot].Sequence * 1) {
      swap(arr, i, index);
      index++;
    }
  }
  swap(arr, pivot, index - 1);
  return index - 1;
}

function partitionReverse (arr, left, right) {     //分区操作
  var pivot = left,                      //设定基准值（pivot）
    index = pivot + 1;
  for (var i = index; i <= right; i++) {
    if (arr[i].DTimestamp * 1 > arr[pivot].DTimestamp * 1) {
      swap(arr, i, index);
      index++;
    }
  }
  swap(arr, pivot, index - 1);
  return index - 1;
}

function swap (arr, i, j) {
  var temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}

/**
 * 计算小数长度
 */
export function obtainLength (num) {
  // 当num为：null、undefined、''、或者非数字字符时，均返回NaN
  if (num === null || num === undefined || num === '') {
    return NaN
  }
  let isN = isNaN(num);
  if (isN) return NaN
  // 判断是整数/小数
  var x = String(num).indexOf('.') + 1; //小数点的位置
  if (x === 0) return x
  var y = String(num).length - x; //小数的位数
  return y;
}

/**
 *函数节流
*/

export function throttle (func, wait) {
  let previous = 0;
  return function () {
    let now = Date.now();
    let context = this;
    let args = arguments;
    if (now - previous > wait) {
      func.apply(context, args);
      previous = now;
    }
  }
}

/**
* 检查交易端接口是否一致
* @param {key} string
* @param {url} string
*/

export function checkTUrl (url, key) {
  return url.replace(/\.(\w{2,16})\./g, (...arg) => {
    if (arg[1] !== key) { return `.${key}.` }
    else { return arg[0] }
  })
}